<?php

namespace app;

use extend\Table;

class Manage
{

    static $list_fields=['list_fields','edit_fields','search_fields','require_fields','mini_fields'];

    public function __construct()
    {    
        if(!s('qadmin') && !is_admin()){
            return need_login();
        }
    }

    /**
     * 具体表的配置
     * @auth false
     * @return string
     */
    function data(){

        $table = input('table');
        $mode = input('mode');
        $db = db();
        
        // 修改查询条件，增加 mode 的筛选
        $data = $db->where('table_name', $table)
                   ->where('mode', $mode)
                   ->getOne(CONFIG_TABLE);

        if($data){
            foreach (self::$list_fields as $key){
                if(isset($data[$key]) && $data[$key]){
                    $data[$key]=explode(',',$data[$key]);
                }
            }
            $data['field_options']=json_decode($data['field_options'],true);
        }
        return json($data);
    }

    /**
     * 首页
     * @auth false
     * @return void
     */
    function index()
    {
        $tables = Table::getName();
        view('index', $tables);
    }

    function blocks(){

        $db=db();

        $blocks=$db->orderBy('sort', 'ASC')->get(BLOCK_TABLE); 

        //对blocks 根据type进行处理与查询
        $blocks=array_map(function($v) use ($db) {
            if(!$v['table_name']){
                return null;
            }
            $type=$v['type'];
            // 检查 $v['content'] 是否为 null 或空字符串
            $conf = !empty($v['content']) ? json_decode($v['content'], true) : [];
            switch($type){
                case 'count':
                    //判断$conf是否配置sql
                    if(isset($conf['sql']) && $conf['sql']){
                        $result = $db->query($conf['sql']);
                        $v['content'] = $result[0]['count(*)'] ?? 0;
                    } else {
                        //根据table_name表查询数目 
                        $sql = "SELECT COUNT(*) as total FROM " . $v['table_name'];
                        $result = $db->query($sql); 
                        $v['content'] = $result[0]['total'] ?? 0;
                    }
                    break;
            }

            return $v;
        },$blocks); 

        return json(array_filter($blocks));
    }

    /**
     * 字段列表Api
     * @auth false
     * @return string
     */
    function fields()
    {
        $table=input('table');

        $tables=Table::getName();

        if(!in_array($table,array_keys($tables))){
            return json('参数错误');
        }
        $fields=Table::getFields($table); 
        $modes= Table::getModes($table);

        return json(['fields'=>$fields,'modes'=>$modes]);
    }

    /**
     * 保存配置
     * @auth false
     * @return string
     */
    function save(){

        $data=input('');

        unset($data['t'],$data['act']);

        if(!isset($data['field_options'])){
            return $this->index();
        }

        $table=$data['table_name'];
        $mode = $data['mode']??'admin';

        $table_fields=array_keys(Table::getFields($table));


        $has=db()->where('table_name',$table)->where('mode',$mode)->getOne(CONFIG_TABLE);

        foreach (self::$list_fields as $key){
            if(isset($data[$key]) && is_array($data[$key])){
                $data[$key]=array_intersect($data[$key],$table_fields);
                $data[$key]=implode(',',$data[$key]);
            }
        }
        $data['can_create']=in_array($data['can_create'],[false,"false"])?0:1;
        $data['auth']=in_array($data['auth'],[false,"false"])?0:1;

        foreach ($data['field_options'] as $f=>$option){
            if(!in_array($f,$table_fields)) unset($data['field_options'][$f]);
        }

        $data['field_options']=json_encode($data['field_options'],JSON_UNESCAPED_UNICODE);


        $config_table_fields=array_keys(Table::getFields(CONFIG_TABLE)); 

        if($data){
            foreach ($data as $f=>$v){
                if(!in_array($f,$config_table_fields)){
                    unset($data[$f]);
                }
            }
            unset($data['id']);
        }


        if(!$has){
            $res=db()->insert(CONFIG_TABLE,$data);
        }else{
            $res=db()->where('table_name',$table)->where('mode',$mode)->update(CONFIG_TABLE,$data);
        }

        return $res?json('保存成功'):json('操作失败!',0);
    }


    function sort()
    {
        $data=input();
        $update=[
            $data['type']=>implode(',',$data['fields'])
        ];
        db()->where('mode',$data['mode'])->where('table_name',$data['table'])->update(CONFIG_TABLE,$update);
        return json('');
    }

    static $page = 1;
    static $page_num = 20;

    function data_list(){

        $data=input();

        self::$page = $data['page'] ?? 1;

        $config=Table::getConfig($data['table'],$data['mode']);

        $limit_start = self::$page * (self::$page_num) - (self::$page_num);
        $limit_end = self::$page * (self::$page_num);

        $list_fields=$config['list_fields'];
        isset($config['pk']) && $list_fields[]=$config['pk'];
        $list_fields=array_filter($list_fields);


        $list=db()->get($config['table_name'], [$limit_start, $limit_end],$list_fields);


        $data['list']=$list;
        $data['config']=$config;

        view('list', $data);
    }


    /**
     * 保存块数据
     * @auth false
     * @return string
     */
    function save_block()
    {
        $data = input(''); 
        // 移除不需要的字段
        unset($data['t'],$data['_h_'], $data['act'],$data['PHPSESSID']);
        
        $db = db();
        
        // 检查是否存在id，决定是更新还是插入
        if (isset($data['id']) && !empty($data['id']) && $data['id']) {
            $id = (int)$data['id'];
            unset($data['id']);  // 从更新数据中移除id 
            // 更新现有记录
            $res = $db->where('id', $id)->update(BLOCK_TABLE, $data);
            $message = '更新成功';
        } else {
            unset($data['id']);
            // 插入新记录
            $res = $db->insert(BLOCK_TABLE, $data);
            $message = '添加成功';
        }
        
        // 返回操作结果
        return $res ? json($message) : json('操作失败', 0);
    }
}